package com.itheima.a11threadsafe3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread extends Thread{

    static int ticket = 0 ;

    static Lock lock = new ReentrantLock() ;

    /**
     */
    @Override
    public void run() {
        while(true){

            /**
             * 每一次线程退出时(被抢占CPU) 都会关锁 但是有可能直接break出去了就没关锁 ， 导致其他线程一致等待锁打开 程序就不会结束
             * 所以要无论怎么样都要执行关锁 -- >用 try - catch - finally
             * 写在这里有可能
             */

            lock.lock();

            try {
                if (ticket == 100) {
                    break;
                }

                else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(getName() + '@' + ticket ++ );
                }
            } finally {
                lock.unlock();
            }


        }
    }
}
